$(function(){
    $('#customAreaTree').window('close');
    var flag='addData';
    //获取下拉列表的静态数据  begin
    //1.客户状态
    $.ajax({
        type: "post",
        url: "/staticData/getStaticDataByCodeType?codeType="+"CUSTOMER_STATUS",
        async:false,
        dataType:"json",
        contentType:"application/json",
        success:function(result){
            if(result.iBsStaticDataList !=null){
                $('#custStatus').combobox({
                    data : result.iBsStaticDataList,
                    valueField:'codeValue',
                    textField:'codeName'
                });
            }
        },error:function(result){

            return false;
        }

    });
    //2.证件类型
    $.ajax({
        type: "post",
        url: "/staticData/getStaticDataByCodeType?codeType="+"ID_TYPE",
        dataType: "json",
        success:function(result) {
            if (result.iBsStaticDataList!= null) {
                $('#custCertType').combobox({
                    data : result.iBsStaticDataList,
                    valueField:'codeValue',
                    textField:'codeName'
                });
            }
        }
    });
    //3.客户类型
    $.ajax({
        type: "post",
        url: "/staticData/getStaticDataByCodeType?codeType="+"CUSTOMER_TYPE",
        dataType: "json",
        success:function(result) {
            if (result.iBsStaticDataList!= null) {
                $('#custServiceLevel').combobox({
                    data : result.iBsStaticDataList,
                    valueField:'codeValue',
                    textField:'codeName'
                });
            }
        }
    });
    //4.所属行业
    $.ajax({
        type: "post",
        url: "/staticData/getStaticDataByCodeType?codeType="+"INDUSTRY_TYPE",
        dataType: "json",
        success:function(result) {
            if (result.iBsStaticDataList!= null) {
                $('#vocation').combobox({
                    data : result.iBsStaticDataList,
                    valueField:'codeValue',
                    textField:'codeName'
                });
            }
        }
    });

    //5.联系人列表
    $.ajax({
        type: "post",
        url: "/cm/queryContactListByType/1",
        dataType: "json",
        success:function(result) {
            if (result.iContactList!= null) {
                $('#contactPerson').combobox({
                    data : result.iContactList,
                    valueField:'contId',
                    textField:'contName'
                });
                var data=result.iContactList;
                $('#contactPerson').combobox('select', data[0].contId);
            }
        }
    });

    //客户经理列表

    //end

    $('#createSub').bind('click', function () {
        $("#createSub").linkbutton("disable");
        //生成业务流水，供后面数据使用
        creatDoneCode();
        $("#createSub").linkbutton("enable");
    });

    $('#changeSub').bind('click', function () {
        flag='modifyData';
        //点击修改按钮，新增灰色，新增下级灰色，保存显示，修改灰色
        $("#addCust").linkbutton("disable");
        $("#saveCust").linkbutton("enable");
        $("#modifyCust").linkbutton("enable");
    });

    $('#removeSub').bind('click', function(){
        if(flag== 'addData') {
            $.ajax({
                type: 'POST',
                url: "/cm/addCm",
                data: {
                    custName: $("#custName").val(),
                    //custId: $("#custId").val(),
                    legalCustName:$("#legalCustName").val(),
                    doneCode:$("#doneCode").val(),
                    custCertType:$('#custCertType').combobox('getValue'),
                    custCertCode:$("#custCertCode").val(),
                    custCertEffdate: $("#custCertEffdate").datebox('getValue'),
                    custCertExpire: $("#custCertExpire").datebox('getValue'),
                    custCertAddress:$("#custCertAddress").val(),
                    custServiceLevel:$('#custServiceLevel').combobox('getValue'),
                    contId:$('#contactPerson').combobox('getValue'),
                    vocation:$('#vocation').combobox('getValue'),
                    parentCustId: $("#parentCustId").val(),
                    custStatus:$('#custStatus').combobox('getValue'),
                    fileId:$("#fileId").val(),
                    contractSeq:$("#contractSeq").val()
                    //managerId:$('#managerName').combobox('getValue')

                },
                dataType: "json",
                success: function (result) {
                    $.messager.alert('操作提示:',result.message,'info');
                },
                error: function (result) {
                    $.messager.alert("操作提示", "保存失败","error");
                    return ;
                }
            });
        }
        if(flag== 'modifyData') {
            $.ajax({
                type: 'POST',
                url: "/cm/modifyCust",
                data: {
                    custName: $("#custName").val(),
                    custId: $("#custId").val(),
                    legalCustName:$("#legalCustName").val(),
                    doneCode:$("#doneCode").val(),
                    custCertType:$('#custCertType').combobox('getValue'),
                    custCertCode:$("#custCertCode").val(),
                    custCertEffdate: $("#custCertEffdate").datebox('getValue'),
                    custCertExpire: $("#custCertExpire").datebox('getValue'),
                    custCertAddress:$("#custCertAddress").val(),
                    custServiceLevel:$('#custServiceLevel').combobox('getValue'),
                    contId:$('#contactPerson').combobox('getValue'),
                    vocation:$('#vocation').combobox('getValue'),
                    parentCustId: $("#parentCustId").val(),
                    custStatus:$('#custStatus').combobox('getValue')
                },
                dataType: "json",
                success: function (result) {
                    $.messager.alert('操作提示:',result.message,'info');
                },
                error: function (result) {
                    $.messager.alert("操作提示", "修改失败","error");
                    return ;
                }
            });
        }
    });

//点击查询
    $('#searchCust').bind('click', function(){
        //点击查询按钮，修改显示，新增灰色，新增下级灰色，保存灰色
        changeButton();
        var custName =$("#custName").val();
        if(custName==null || custName.length<1){
            $.messager.alert("操作提示", "请录入客户名称","error");
            return ;
        }else {
            $.ajax({
                type: 'POST',
                url: "/cm/queryCustomer",
                data: {
                    custName: $("#custName").val()
                },
                dataType: "json",
                async:false,
                success: function (result) {
                    if (result.customer!= null) {
                        var custData=result.customer;
                        $("#custCertCode").val(custData.custCertCode);
                        $("#custCertAddress").val(custData.custCertAddress);
                        $('#contactPerson').combobox('setValue', custData.contId);
                        $("#custId").val(custData.custId);
                        $("#doneCode").val(custData.doneCode);
                        $('#vocation').combobox('setValue',custData.vocation)
                        var custCertEfftimes = new Date(parseInt("/Date("+custData.custCertEffdate.time+")/".substr(6, 13))).toLocaleDateString().replace("/", "-").replace("/", "-");
                        var custCertExpiretimes = new Date(parseInt("/Date("+custData.custCertExpire.time+")/".substr(6, 13))).toLocaleDateString().replace("/", "-").replace("/", "-");
                        $("#custCertEffdate").datebox('setValue',custCertEfftimes);
                        $("#custCertExpire").datebox('setValue',custCertExpiretimes);
                        $("#custServiceLevel").combobox('setValue',custData.custServiceLevel);
                        $("#custCertType").combobox('setValue',custData.custCertType);
                        $("#parentCustId").val(custData.parentCustId);
                        $("#legalCustName").val(custData.legalCustName);
                        $("#custStatus").combobox('setValue',custData.custStatus);
                        queryParentCustName(custData.parentCustId);

                    }else{
                        $.messager.alert('操作提示','此用户不存在!','info');
                        return ;
                    }
                },
                error: function (result) {

                }
            });
        }

    });

    /**
     * 文件上传
     */
        //$('#fileUpload').bind('click', function(){
        //    if(flag== 'addData'){
        //        creatDoneCode();
        //    }
        //    //生成file主键
        //    creatFileId();
        //    $.ajaxFileUpload({
        //        url:'/dealFile/uploadFile?doneCode='+$("#doneCode").val()+'&fileId='+$("#fileId").val(),//用于文件上传的服务器端请求地址
        //        fileElementId:'paramFile',//文件上传控件的id
        //        secureuri:false,
        //        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        //        dataType:"json",//服务器返回的数据类型
        //        success: function (data,status){
        //            $('#resultText').html(data.result);
        //            var repObj =eval(data);
        //        },
        //        error: function (data,status,e){
        //            alert("服务中断或连接超时导致通信失败！");
        //            alert(e);
        //        }
        //    })
        //});
    $('#UploadSpecialRecommendPic').bind('click', function(){
        if(flag== 'addData'){
            creatDoneCode();
        }
        //生成file主键
        creatFileId();
        $.ajaxFileUpload({
            url :'/dealFile/uploadFile?doneCode='+$("#doneCode").val()+'&fileId='+$("#fileId").val(),
            secureuri : false,
            fileElementId : 'specialrecommendfile',
            dataType : 'json',
            success : function(data, status) {
                $('#specialRecommendPic').html(data.result);
            },
            error : function(data, status, e) {
                alert(e);
            }
        });
    });



    //控制按钮的显示与隐藏
    initButton();

    function initButton() {
        flag='addData';
        //新增按钮显示，保存按钮灰色，修改按钮灰色，新增下级客户显示
        $("#addCust").linkbutton("enable");
        $("#saveCust").linkbutton("disable");
        $("#modifyCust").linkbutton("disable");
    }

    $("#contactPerson").combobox({
        onChange: function (n,o) {
            //查询对应的手机号码
            queryTel(n);
        }
    });
    function queryTel(contId){
        $.ajax({
            type: "post",
            url: "/cm/queryContactByContId/"+contId,
            dataType: "json",
            success:function(result) {
                if (result.iContact!= null) {
                    var tel= result.iContact.contMobile;
                    $("#contactTel").val(tel);
                }
            }
        });
    }

});

function myformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
}
function myparser(s) {
    if (!s) return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0], 10);
    var m = parseInt(ss[1], 10);
    var d = parseInt(ss[2], 10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        return new Date(y, m - 1, d);
    } else {
        return new Date();
    }
}

/**
 * 点击上传按钮判断有没生成过序列，并且点击的是否是新增按钮 ，
 * 没有则需要生成序列，并且将序列放入页面中以便保存客户信息时使用
 */
function creatDoneCode(){
    var doneCode =$("#doneCode").val();
    if(doneCode ==null|| doneCode=="" || doneCode =='undefined'){
        $.ajax({
            type: 'POST',
            url: "/gateway/imssoap/getDoneCode",
            dataType: "json",
            async:false,
            success: function (result) {
                if (result.doneCode!= null) {
                    $("#doneCode").val(result.doneCode);
                }else{
                    $.messager.alert('操作提示','未获取到操作流水','info');
                    return ;
                }
            },
            error: function (result) {

            }
        });
    }
}

//点击查询按钮，修改显示，新增灰色，新增下级灰色，保存灰色
function changeButton(){
    $("#addCust").linkbutton("disable");
    $("#saveCust").linkbutton("disable");
    $("#modifyCust").linkbutton("enable");
}


function selectCustTree() {
    $('#addForm1').form('clear');
    $('#customAreaTree').window({
        title:'客户组织结构',
        iconCls:'icon-add',
        width:200,
        height:300,
        modal: true,
        shadow: true,
        collapsible:false,
        minimizable:false,
        maximizable:false
    });
    initCustomAreaTree();
    $('#customAreaTree').window('move',{top:10,left:10});
    $('#customAreaTree').window('open');
}

function initCustomAreaTree(){
    $("#msg1").attr("innerHTML","数据读取中，请稍候。。。。。。");
    var treeOps = {};
    treeOps.url = "/cm/queryCustomerTreeById/0";
    treeOps.onBeforeExpand = function(node,param){
        if(node.id==null){

        }else{
            $("#euTreeOne").tree('options').url ="/cm/queryCustomerTreeById/"+node.id;
        }

    };
    treeOps.onLoadSuccess = function(node,param){
        $("#msg1").attr("innerHTML","");
    };

    $("#euTreeOne").tree(treeOps);
}

function selectCustomArea() {
    var selectedNode = $("#euTreeOne").tree("getSelected");
    if (selectedNode == null){
        $.messager.alert('提示信息','请选择区域','error');
    } else {
        $("#parentCustName").val(selectedNode.text);
        $("#parentCustId").val(selectedNode.id);
        $('#customAreaTree').window('close');
    }
}

//查询父节点的名称
function queryParentCustName(parentCustId){
    if(parentCustId == 0){
        var custName =$("#custName").val()
        $("#parentCustName").val(custName);
    }else{
        $.ajax({
            type: 'POST',
            url: "/cm/queryCustById/"+parentCustId,
            dataType: "json",
            async:false,
            success: function (result) {
                if (result.customer!= null) {
                    var custData=result.customer;
                    $("#parentCustName").val(custData.custName);
                }
            },
            error: function (result) {

            }
        });
    }

}
